﻿<template>
  <a-drawer
    :destroyOnClose="true"
    :loading="loading"
    :title="title"
    :visible="visible"
    width="90%"
    @close=" () => { this.visible = false }">
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <div class="mainInfo">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="字典名称" prop="DicName">
              <a-input v-model="entity.DicName" autocomplete="off" placeholder="字典名称"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="字典值" prop="DicKey">
              <a-input v-model="entity.DicKey" autocomplete="off" placeholder="字典值"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="上级节点" prop="ParentId">
              <a-tree-select v-model="entity.ParentId" :treeData="ParentIdTreeData" allowClear placeholder="请选择上级菜单" treeDefaultExpandAll></a-tree-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="排序" prop="Sort">
              <a-input-number v-model="entity.Sort" autocomplete="off" placeholder="越小越靠前" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="是否启用" prop="Enable">
              <a-radio-group v-model="entity.Enable" :default-value="false" button-style="solid">
                <a-radio-button :value="true"> 是</a-radio-button>
                <a-radio-button :value="false"> 否</a-radio-button>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="系统必备" prop="IsSystem">
              <a-radio-group v-model="entity.IsSystem" :default-value="false" button-style="solid">
                <a-radio-button :value="true"> 是</a-radio-button>
                <a-radio-button :value="false"> 否</a-radio-button>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="备注" prop="Remark">
              <a-textarea v-model="entity.Remark" autocomplete="off" placeholder="备注"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
      <div class="detailInfo">
        <div class="itemButton">
          <a-button :loading="loading" icon="plus" type="primary" @click="addTable"> 添加</a-button>&nbsp;
          <a-button
            v-if="hasPerm('Base_DictionaryDetails.Delete')"
            :disabled="!hasSelected()"
            :loading="loading"
            icon="minus"
            type="primary"
            @click="handleDelete('',[],selectedRows)"> 删除
          </a-button>&nbsp;
          <a-button :disabled="this.DetaiData.length===0" :loading="loading" icon="delete" type="danger" @click="clearAll"> 全部清空</a-button>
        </div>
        <a-table
          id="detailsTable"
          ref="table"
          :bordered="true"
          :columns="columns"
          :dataSource="DetaiData"
          :loading="loading"
          :pagination="pagination"
          :rowKey="(row,index) => row.Id||index"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'checkbox' }"
          :scroll="{ y: tableHight }"
          size="small"
          @change="handleTableChange">
          <template slot="DicName" slot-scope="text, record, index">
            <a-form-model-item :wrapperCol="{ span:24 }" :prop="'DicName' +`${ index }`" :rules="[{ validator: validEmpty(index,'DicName', '请输入字典名'), trigger: 'blur' }]">
              <a-input v-model="record.DicName" size="small" placeholder="请输入字典名"></a-input>
            </a-form-model-item>
          </template>
          <template slot="DicValue" slot-scope="text, record, index">
            <a-form-model-item :wrapperCol="{ span:24 }" :prop="'DicValue' +`${ index }`" :rules="[{ validator: validEmpty(index,'DicValue', '请输入字典名'), trigger: 'blur' }]">
              <a-input v-model="record.DicValue" size="small" placeholder="请输入字典值"></a-input>
            </a-form-model-item>
          </template>
          <template slot="Enable" slot-scope="text, record">
            <a-radio-group v-model="record.Enable" :default-value="false" button-style="solid">
              <a-radio-button :value="true"> 是</a-radio-button>
              <a-radio-button :value="false"> 否</a-radio-button>
            </a-radio-group>
          </template>
          <template slot="IsSystem" slot-scope="text, record">
            <a-radio-group v-model="record.IsSystem" :default-value="false" button-style="solid">
              <a-radio-button :value="true"> 是</a-radio-button>
              <a-radio-button :value="false"> 否</a-radio-button>
            </a-radio-group>
          </template>
          <template slot="Remark" slot-scope="text, record">
            <a-input v-model="record.Remark" size="small"></a-input>
          </template>
          <span slot="ModifyDate" slot-scope="ModifyDate">{{ timeFormat(ModifyDate, 'YYYY-MM-DD HH:mm') }}</span>
          <template slot="action" slot-scope="text, record, index">
            <a v-if="hasPerm('Base_DictionaryDetails.Delete')" @click="handleDelete(index, [record.Id],[record])">删除</a>
          </template>
        </a-table>
      </div>
    </a-form-model>
    <div :style="{ position: 'absolute', right: 0, bottom: 0, width: '100%', borderTop: '1px solid #e9e9e9', padding: '10px 16px', letterSpacing: '20px', background: '#fff', textAlign: 'right', zIndex: 1 }">
      <a-button @click="close"> 取消</a-button>&nbsp;
      <a-button :loading="loading" type="primary" @click="handleSubmit"> 保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import moment from 'moment'

const columns = [
  // { title: '更新时间', dataIndex: 'UpdateTime', width: '10%' },
  { title: '字典名称', dataIndex: 'DicName', scopedSlots: { customRender: 'DicName' } },
  { title: '字典值', dataIndex: 'DicValue', scopedSlots: { customRender: 'DicValue' } },
  { title: '修改人姓名', dataIndex: 'Modifier', width: '8%', align: 'center', scopedSlots: { customRender: 'Modifier' } },
  { title: '修改时间', dataIndex: 'ModifyDate', width: '8%', align: 'center', scopedSlots: { customRender: 'ModifyDate' } },
  { title: '是否启用', dataIndex: 'Enable', width: '8%', align: 'center', scopedSlots: { customRender: 'Enable' } },
  { title: '是否系统必须', dataIndex: 'IsSystem', width: '8%', align: 'center', scopedSlots: { customRender: 'IsSystem' } },
  { title: '备注', dataIndex: 'Remark', scopedSlots: { customRender: 'Remark' } },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
]

export default {
  props: {
    parentObj: {
      type: Object,
      default () {
        return {}
      }
    },
    disabled: {
      type: Boolean,
      required: false
    }
  },
  data () {
    return {
      tableHight: 570, // 表格高度
      selectedRows: [],
      selectedRowKeys: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: {
        field: 'Id',
        order: 'desc'
      },
      columns,
      DetaiData: [],
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 }
      },
      visible: false,
      loading: false,
      entity: {},
      rules: {
        Sort: [{
          required: true,
          message: '请输入排序编号',
          trigger: 'blur'
        }],
        DicName: [{
          required: true,
          message: '请输入字典名称',
          trigger: 'blur'
        }],
        DicKey: [{
          required: true,
          message: '请输入字典Key',
          trigger: 'blur'
        }]
      },
      title: '',
      ParentIdTreeData: [],
      SelectParentId: null
    }
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHight = this.getTableHeight(true) - 80
    })
  },
  methods: {
    // 子表删除
    handleDelete (index, ids, rows) {
      if (this.title === '编辑字典信息') {
        if (ids.length === 0 && rows.length > 0) {
        } else if (ids.length === 1 && rows.length === 1 && ids[0] === undefined) {
          this.DetaiData.splice(index, 1)
          this.pagination.total = this.DetaiData.length
        } else {
          this.$confirm({
            title: '确认删除吗?',
            onOk: () => {
              this.$http.post('/Base_BasicData/Base_DictionaryDetails/DeleteData', ids).then(res => {
                if (res.Success) {
                  this.DetaiData.splice(index, 1)
                  this.pagination.total = this.DetaiData.length
                  this.$message.success('删除成功')
                  this.$emit('returnMain')
                } else {
                  this.$message.error(res.Msg)
                }
              })
            }
          })
        }
      } else {
        this.DetaiData.splice(index, 1)
        this.pagination.total = this.DetaiData.length
      }
    },
    // 添加一行记录
    addTable () {
      this.DetaiData.push({
        DicName: '',
        DicValue: '',
        Enable: true,
        Modifier: '',
        ModifyDate: moment(),
        ExpectedDate: moment(),
        IsSystem: false,
        Remark: ''
      })
      this.pagination.total = this.DetaiData.length
      this.toLastPage()
      this.toLastTableRow()
    },
    // 清空所有子表数据
    clearAll () {
      const that = this
      this.loading = true
      this.$confirm({
        title: '是否清空全部子项记录信息?',
        onOk: () => {
          that.$http.post('/Base_BasicData/Base_DictionaryDetails/DeleteDataByCondition', [{
            Condition: 'Dic_MID',
            Keyword: that.entity.Id
          }]).then(res => {
            if (res.Success) {
              that.DetaiData = []
              that.pagination.total = that.DetaiData.length
              that.$message.success('删除成功')
              that.loading = false
              this.$emit('returnMain')
            } else {
              that.$message.error(res.Msg)
              that.loading = false
            }
          })
        },
        onCancel: () => {
          that.loading = false
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    // 获取选中的行
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
    },
    // 跳转最后一页
    toLastPage () {
      const pagination = { ...this.pagination }
      pagination.current = Math.ceil(pagination.total / pagination.pageSize)
      this.pagination = pagination
    },
    // 跳转最后一行
    toLastTableRow () {
      const allDom = document.getElementById('detailsTable').getElementsByClassName('ant-table-body')
      const list = Array.from(allDom)
      list.forEach(item => {
        item.scrollTop = window.innerHeight + item.scrollTop
      })
    },
    close () {
      this.visible = false
      this.entity = {}
    },
    // 初始化页面信息
    init (id) {
      this.visible = true
      this.DetaiData = []
      this.ParentIdTreeData = []
      this.pagination.total = this.DetaiData.length
      this.entity = {}
      this.selectedRowKeys = []
      this.selectedRows = []
      const Ids = id ? [id] : []
      this.$http.post('/Base_BasicData/Base_DictionaryMain/GetTreeDataList', Ids).then(resJson => {
        if (resJson.Success) {
          this.ParentIdTreeData = resJson.Data
        }
      })
      this.SelectParentId = '0'
      this.entity = {
        Id: '',
        Enable: true,
        IsSystem: false,
        ParentId: null,
        ModifyDate: moment()
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    // 打开页面事件
    openForm (id, title) {
      this.init(id)
      this.title = title
      if (id) {
        this.loading = true
        this.$http.post('/Base_BasicData/Base_DictionaryMain/GetTheData', { id: id }).then(resJson => {
          this.loading = false
          this.entity = resJson.Data
          this.SelectParentId = this.entity.ParentId
          if (this.entity.ParentId == null || this.entity.ParentId === '0' || this.entity.ParentId.toLowerCase() === 'top') {
            this.entity.ParentId = null
          }
          this.DetaiData = resJson.Data.DictionaryDetailsList
          if (this.DetaiData) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Data.DictionaryDetailsList.length
            this.pagination = pagination
          }
          if (this.entity['ModifyDate']) {
            this.entity['ModifyDate'] = moment(this.entity['ModifyDate'])
          }
        })
      }
    },
    // 保存提交数据库
    handleSubmit () {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        const datalist = this.DetaiData.map(item => {
          return item.DicName
        })
        const item = Array.from(new Set(datalist))
        if (item.length < datalist.length) {
          this.$message.error('名字不能重复')
          return
        }
        const entityData = { ...this.entity }
        if (entityData.ParentId == null) { entityData.ParentId = this.SelectParentId }
        entityData.DictionaryDetailsList = [...this.DetaiData]
        this.loading = true
        this.$http.post('/Base_BasicData/Base_DictionaryMain/SaveData', entityData).then(resJson => {
          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.loading = false
            this.visible = false
            this.$emit('returnMain')
          } else {
            this.$message.error(resJson.Msg)
            this.loading = false
          }
        })
      })
    },
    // 非空校验
    validEmpty (index, name, tips) {
      return (rule, value, callback) => {
        const data = this.DetaiData[index][name]
        if (!data) {
          this.$message.warning('列表第' + (index + 1) + '行：' + tips)
          callback(tips || '必填')
        } else {
          callback()
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.itemButton {
  width: 100%;
  border-style: solid;
  border-width: 1px 1px 0 1px;
  border-color: #E8E8E8;
  border-radius: 10px 10px 0 0;
  padding: 20px 10px;
  background: #fff;
  text-align: left;
  z-index: 1;
}

::v-deep .mainInfo {
  //重写表单样式
  .ant-form-item {
    padding: 0
  }

  .has-error .ant-form-explain {
    text-align: right;
  }

  .show-help-leave {
    text-align: right;
  }
}

::v-deep .detailInfo {
  //重写表单样式
  .ant-form-item {
    margin: 0;
    padding: 0
  }

  .has-error .ant-form-explain {
    text-align: right;
    display: none;
  }

  .show-help-leave {
    display: none;
    text-align: right;
  }
}
</style>
